import { HCode } from "./../common/code";
import { HPagingResponse, HResponse } from "./../common/response";
import { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
import { map, Observable } from "rxjs";
import { Response } from 'express';

// 统一输出格式
export class HResponseTransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
      const ctx = context.switchToHttp();
      const response = ctx.getResponse<Response>();
      response.status(HCode.success);
      return next.handle().pipe(
        map((data: any) => {
          if (data.paging) {
            return new HPagingResponse(data.data, data.paging, data.reference);
          }
          if (data.reference) {
            return new HResponse(data.data, data.reference);
          }
          return new HResponse(data);
        })
      );
  }
}